package nginx_logic

import (
	"context"
	"strings"
	"time"
	"yunzhan/common/utils"
	agent "yunzhan/rpc-server/pb"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ModifyNginxConfigLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewModifyNginxConfigLogic 更新Nginx配置
func NewModifyNginxConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ModifyNginxConfigLogic {
	return &ModifyNginxConfigLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ModifyNginxConfigLogic) ModifyNginxConfig(req *types.ModifyConfigRequest) (resp *types.BaseConfigResponse, err error) {
	if req.ClusterID == "" || req.NodeHost == "" || req.Content == "" {
		return &types.BaseConfigResponse{
			Code:    500,
			Message: "Invalid request parameters",
		}, nil
	}

	agentPort := strings.Split(l.svcCtx.Config.RpcService.ListenOn, ":")[1]

	conn, err := utils.SafeNewClient(req.NodeHost, agentPort)
	if err != nil {
		logx.Errorf("Failed to create RPC connection: %v", err)
		return &types.BaseConfigResponse{
			Code:    500,
			Message: "Failed to create RPC connection",
		}, err
	}

	ctx, cancel := context.WithTimeout(l.ctx, 10*time.Second)
	defer cancel()

	client := agent.NewNginxDeployClient(conn.Conn())
	nginxConfig, err := client.ModifyNginxConf(ctx, &agent.ModifyNginxConfRequest{
		NodeHost:  req.NodeHost,
		ClusterID: req.ClusterID,
		Content:   req.Content,
	})
	if err != nil {
		logx.Errorf("Failed to modify Nginx config: %v", err)
		return &types.BaseConfigResponse{
			Code:    500,
			Message: "Failed to modify configuration",
		}, err
	}

	if nginxConfig == nil {
		return &types.BaseConfigResponse{
			Code:    500,
			Message: "Received nil response from server",
		}, nil
	}

	return &types.BaseConfigResponse{
		Code:    nginxConfig.Code,
		Message: nginxConfig.Message,
		Data:    nginxConfig.Content,
	}, nil
}
